package com.admin.model;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.admin.util.MD5;
import com.admin.util.Page;
import com.admin.util.UtilTools;

public class Sys_User extends MyDB<Sys_User> {
	private static final long serialVersionUID = 1591699979286078018L;
	public static final Sys_User dao = new Sys_User();
	public Sys_User() {
		tableName = "sys_users";
	}
	private Log logger = LogFactory.getLog(Sys_User.class);
	public static final String AllSelect = "select * from sys_user";

	/**
	 * 分页查询
	 */
	public void listByPage(String[] params,Page<Sys_User> page){
		// 查询数量
		StringBuffer sb1 = new StringBuffer();
		sb1.append(" select count(*) count from sys_users u1 ");
		sb1.append(" inner join sys_users u2 on u1.id = u2.user_id_created ");
		sb1.append(" where 1 = 1 ");
		if(null != params){
			for (String param : params) {
				if(null != param){
					sb1.append(" and " + param);
				}
			}
		}
		page.setTotalCount(getCount(sb1.toString()));
		// 查询结果集
		StringBuffer sb2 = new StringBuffer();
		sb2.append(" select u1.username createName,u2.* from sys_users u1 ");
		sb2.append(" inner join sys_users u2 on u1.id = u2.user_id_created ");
		sb2.append(" where 1=1");
		if(null != params){
			for (String param : params) {
				if(null != param){
					sb2.append(" and " + param);
				}
			}
		}
		if(UtilTools.isNotNull(page.getOrderField())){
			sb2.append(" order by "+ page.getOrderField() +" "+ page.getOrderDirection());
		}
		sb2.append(" limit "+page.getStartIndex()+","+page.getPageSize());
		List<Sys_User> list = dao.find(sb2.toString());
		/*for (Sys_User user : list) {
			String roleNames = this.getRoles(user.getLong("id"));
			user.set("roles",roleNames);
		}*/
		page.setResult(list);
	}
	
	// 通过用户id得到角色
	public String getRoles(Long userId){
		StringBuffer sb = new StringBuffer();
		StringBuffer sql = new StringBuffer();
		sql.append(" select r.name from sys_roles r  ");
		sql.append(" inner join sys_user_role ru on ru.role_id = r.id ");
		sql.append(" inner join sys_users u on u.id = ru.user_id ");
		sql.append(" where u.id = "+userId);
		List<Sys_User> list = dao.find(sql.toString());
		for (Sys_User sys_User : list) {
			sb.append(sys_User.get("name")+",");
		}
		if(null != sb && sb.length() > 0){
			return sb.substring(0,sb.length()-1);
		}
		return "暂无";
	}
	
	// 查看详情
	public Sys_User getUser(Long id){
		List<Sys_User> list = dao.query(new String[]{"id="+id});
		if(null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	
	// 修改密码
	public boolean updatePwd(Long id,String pwd){
		String sql = "update sys_users set password = '"+ MD5.encode(pwd) +"' where id = "+id;
		return dao.operateBySql(sql);
	}
	
	// 修改最后登录时间和登录次数
	public boolean updateLoginInfo(Long id){
		String sql = "update sys_users set date_last_login = now(),logincount = logincount + 1 where id = '"+ id +"'";
		return dao.operateBySql(sql);
	}
	
	// 删除
	public boolean del(String[] ids){
		String sql = "update sys_users set deleted = 1 where id in ("+ UtilTools.getStr(ids) +")";
		return dao.operateBySql(sql);
	}
	
	// 重置密码为123456
	public boolean resetPwd(String[] ids){
		String sql = "update sys_users set password = '"+ MD5.encode("123456") +"' where id in ("+ UtilTools.getStr(ids) +")";
		return dao.operateBySql(sql);
	}
	
	// 更新状态(将可用更新为不可用，不可用更新为可用)
	public boolean updateState(String[] ids){
		String sql = "update sys_users set active = (if(active = 1,0,1)) where id in ("+ UtilTools.getStr(ids) +")";
		return dao.operateBySql(sql);
	}
	
	// 通过用户id得到用户姓名
	public String getUserName(String[] ids){
		String sql = "select username from sys_users where id in ("+ UtilTools.getStr(ids) +")";
		List<Sys_User> list = dao.find(sql);
		StringBuffer userNames = new StringBuffer();
		for (Sys_User user : list) {
			userNames.append(user.getStr("username")+",");
		}
		return userNames.substring(0,userNames.length()-1);
	}
	
	// 更新用户角色
	public boolean updateRole(String[] userIds,String roleIds) throws Exception{
		boolean result = false;
		// 先删除用户原有角色
		StringBuffer sb = new StringBuffer();
		for (String string : userIds) {
			sb.append(string+",");
		}
		String sql = "delete from sys_user_role where user_id in ("+ sb.substring(0,sb.length()-1) +")";
		result = dao.operateBySql(sql);
		if(result){
			if(null != roleIds && roleIds != ""){
				// 再为用户赋予新角色
				StringBuffer sbSql = new StringBuffer();
				sbSql.append(" insert into sys_user_role(role_id,user_id) values ");
				for(String userId : userIds){
					for (String roleId : roleIds.split(",")) {
						if(!roleId.equals("0")){
							sbSql.append(" ("+ roleId +","+ userId +") "+",");
						}
					}
				}
				result = dao.operateBySql(sbSql.substring(0,sbSql.length()-1));
			}
			if(result){
				// 修改用户角色名称
				String sql1 = "update sys_users set roles = '' where id in ("+ UtilTools.getStr(userIds) +")";
				if(null != roleIds && roleIds != ""){
					String ids = UtilTools.getStr(roleIds.split(","));
					StringBuffer roles = new StringBuffer();
					List<Roles> list = Roles.dao.query(new String[]{"id in ("+ ids +")"});
					for (Roles role : list) {
						roles.append(role.getStr("name")+",");
					}
					sql1 = "update sys_users set roles = '"+ roles.substring(0,roles.length()-1) +"' where id in ("+ UtilTools.getStr(userIds) +")";
				}
				result = dao.operateBySql(sql1);
			}
			
		}
		return result;
	}
	
	// 更新用户来源
	public boolean updateOrdersSource(String[] userIds,String sourceIds) throws Exception{
		boolean result = false;
		// 先删除用户原有来源
		StringBuffer sb = new StringBuffer();
		for (String string : userIds) {
			sb.append(string+",");
		}
		String sql = "delete from sys_user_source where user_id in ("+ sb.substring(0,sb.length()-1) +")";
		result = dao.operateBySql(sql);
		if(result){
			if(null != sourceIds && sourceIds != ""){
				// 再为用户赋予新来源
				StringBuffer sbSql = new StringBuffer();
				sbSql.append(" insert into sys_user_source(source_id,user_id) values ");
				for(String userId : userIds){
					for (String roleId : sourceIds.split(",")) {
						if(!roleId.equals("0")){
							sbSql.append(" ("+ roleId +","+ userId +") "+",");
						}
					}
				}
				result = dao.operateBySql(sbSql.substring(0,sbSql.length()-1));
			}
			if(result){
				// 修改用户来源名称
				String sql1 = "update sys_users set sources = '' where id in ("+ UtilTools.getStr(userIds) +")";
				if(null != sourceIds && sourceIds != ""){
					String ids = UtilTools.getStr(sourceIds.split(","));
					StringBuffer sources = new StringBuffer();
					List<OrdersSource> list = OrdersSource.dao.query(new String[]{"id in ("+ ids +")"});
					for (OrdersSource source : list) {
						sources.append(source.getStr("source_name")+",");
					}
					sql1 = "update sys_users set sources = '"+ sources.substring(0,sources.length()-1) +"' where id in ("+ UtilTools.getStr(userIds) +")";
				}
				result = dao.operateBySql(sql1);
			}
			
		}
		return result;
	}
}
